03. Test Doubles
Test Doubles
ND079 JPND C3 L5 A03 Test Doubles V3
Types of Test Doubles
A **test double **is any kind of object that acts as a stand-in for an expected dependency in order to facilitate testing.
Dummy: A class that doesn't actually do anything, but fills a required parameter of some method.
Stub: A simple class that always returns a hard-coded value.
Fake: A test double that allows you to customize the response to imitate actual functionality.
Spy: A test double that can keep track of which methods were called. Sometimes they can also track what parameters were used or how often the methods were called.
Mock: A generic term for test doubles, or more specifically, a test double that can prepare specific responses for different kinds of input.
Examples
public class DummySalesService implements SalesService {
@Override
public String fizzBuzz(int i) {
}
}
public class StubSalesService implements SalesService {
@Override
public String fizzBuzz(int i) {
return "Buzz"; //always returns Buzz
}
}
public class FakeSalesService implements SalesService {
private String returnValue;
public FakeSalesService(String returnValue) {
this.returnValue = returnValue;
}
@Override
public String fizzBuzz(int i) {
return returnValue;
}
}
public class SpySalesService implements SalesService {
//tracks number of calls and the parameters used
private int numFizzBuzzCalled;
private List<Integer> parameters = new ArrayList<>();
@Override
public String fizzBuzz(int i) {
numFizzBuzzCalled++;
parameters.add(i);
return null;
}
public int getNumFizzBuzzCalled() { return numFizzBuzzCalled; }
public List<Integer> getParameters() { return parameters; }
}
public class MockSalesService implements SalesService{
//stores responses for inputs
private Map<Integer, String> returnValues = new HashMap<>();
@Override
public String fizzBuzz(int i) {
return returnValues.getOrDefault(i, null);
}
//allows users to customize return values programmatically
public void setReturnForInput(int i, String val) {
returnValues.put(i, val);
}
}